function getResult(code, msg) {
  return {
    resultCode: code,
    msg: msg
  }
}

function _fetch(fetch_promise, timeout) {
  let abort_fn = null;
  const abort_promise = new Promise((resolve, reject) => {
    abort_fn = function() {
      resolve(getResult(400, "请求超时"))
    };
  });
  const abortable_promise = Promise.race([
    fetch_promise,
    abort_promise
  ]);
  setTimeout(function(){
    abort_fn();
  }, timeout);

  return abortable_promise;
}
function fetch_post_promise(url, params) {
  return new Promise((resolve, reject) => {
    fetch(url,{
      method: 'POST',
      headers: { 'Accept': 'application/json', 'Content-Type': 'application/json'},
      body: JSON.stringify(params),
    }).then((response) => {
      return response.json();
    }).then((jsonData) => {
      resolve(jsonData);
    }).catch((err) => {
      resolve(getResult(400, "请求超时"))
      // reject(err);  //这里可以使用resolve(err),将错误信息传回去
      if (err.message === 'Network request failed'){
        console.log('网络出错');
      } else if (err === 'abort promise'){
        console.log('请求超时');
      }
    })
  })
}

function fetch_get_promise(url, params) {
  return new Promise((resolve, reject) => {
    fetch(url,{
      method: 'GET',
      headers: { 'Accept': 'application/json', 'Content-Type': 'application/json'},
    }).then((response) => {
      return response.json()
    }).then((jsonData) => {
      resolve(jsonData)
    }).catch((err) => {
      resolve(getResult(400, "请求失败"))
      if (err.message === 'Network request failed'){
        console.log('网络出错');
      } else if (err === 'abort promise'){
        console.log('请求超时');
      }
    })
  })
}


export async function post(url, body, timeout=30000) {
  const uri = encodeURI(url)
  console.log(`post ${url} with ${JSON.stringify(body)}`)
  const resp = await _fetch(fetch_post_promise(url, body), 30000)
  console.log(`resp is `, resp)
  return resp
}

export async function get(url, body) {
  const uri = encodeURI(url)
  console.log(`get ${url} with ${JSON.stringify(body)}`)
  const resp = await _fetch(fetch_get_promise(url, body = {}), 30000)
  console.log(`resp is `, resp)
  return resp
}
